
//google map api v3 
var google_map_api_v3_url="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places";
document.write('<'+'script src="'+google_map_api_v3_url+'" type="text/javascript">' + '<'+'/script>');
var mapUtil=null;
$(function() {
	if (mapUtil===null&&typeof mapUtilConfig === "undefined")
		mapUtil = new KSR.MapUtil({});
	else if  (mapUtil===null)
		mapUtil = new KSR.MapUtil(mapUtilConfig);
		
	mapUtil.init();
});
KSR.MapUtil=function(config){
	var defaults={
		mapDivId:"ksr-map",
		mapOptions:{
		      zoom: 10,
		      center: new google.maps.LatLng(38.889813, -77.008067),
			  mapTypeControl:false,
			  streetViewControl:false,
		      mapTypeId: google.maps.MapTypeId.ROADMAP,
		      panControl: false,
		      zoomControl: true,
		      zoomControlOptions: {
		        style: google.maps.ZoomControlStyle.SMALL
		      }		      
		},
		centerPlace:null,
		centerMarkerImage:{
			pinUrl:"/ksr/images/main-pin-orange.png",
			shadowUrl:"/ksr/images/main-pin-shadow.png"
				,
			anchor:{
				x:9,
				y:25
			}
		},
		polygonOptions:{},
		markerOptions:{},
		pinColor:"FE7569",
		pinHoverColor:"5bc0de",
		markerImageBaseUrl:"https://chart.googleapis.com/chart?chst=d_map_pin_letter_withshadow&chld=",
		markerHoverImageBaseUrl:"https://chart.googleapis.com/chart?chst=d_map_pin_letter_withshadow&chld="
	};
	this.settings=$.extend(defaults,config);
};
//instance methods
KSR.MapUtil.prototype={
	mapInstance:null,
	markerBounds:null,
	gmarkers:[],
	infoWindow:null,
//	zoomLevelLimited:false,//this is used for limit zoom level to max/min zoom only after fitBounds
	init:function(){
		var self = this, settings = this.settings;
		//config autocomplete
		$(".place-autocomplete").each(function(){
			var input = $(this).get(0);
			var autocomplete = new google.maps.places.Autocomplete(input);
		})
		//init map instance if map div exists
		if ($("#"+settings.mapDivId).length>0){
			google.maps.visualRefresh = true;
			if (settings.centerPlace!=null){
				settings.mapOptions.center=new google.maps.LatLng(settings.centerPlace.lat,settings.centerPlace.lng);
			}
			self.mapInstance=new google.maps.Map(document.getElementById(settings.mapDivId), settings.mapOptions);
			self.markerBounds=new google.maps.LatLngBounds();
		
			if (settings.centerPlace!=null){
				settings.centerPlace.markerImage=new google.maps.MarkerImage(
						settings.centerMarkerImage.pinUrl,
						null,
						null,
						new google.maps.Point(settings.centerMarkerImage.anchor.x,settings.centerMarkerImage.anchor.y)
				);
				settings.centerPlace.shadowImage=new google.maps.MarkerImage(
						settings.centerMarkerImage.shadowUrl,
						null,
						null,
						new google.maps.Point(settings.centerMarkerImage.anchor.x,settings.centerMarkerImage.anchor.y)
				);
				settings.centerPlace.hoverImage=settings.centerPlace.markerImage;
				centerMarker=self.addMarker(self.mapInstance,settings.centerPlace);
//				self.markerBounds.extend(new google.maps.LatLng(settings.centerPlace.lat,settings.centerPlace.lng));	
				var circle = self.drawCircle(settings.centerPlace);
				self.markerBounds = circle.getBounds();
			}
		}
		if (typeof settings.onMapLoadCallback=='function'){
			settings.onMapLoadCallback.call();
		}	
		
	},
	addMarker:function(map,place,markerNum){
		var self = this;
		var point =new google.maps.LatLng(place.lat,place.lng);
		var marker = new google.maps.Marker({
			position:point,
			map:map,
			shadow:place.shadowImage,
			icon:place.markerImage,
		});	
		
		if (typeof place.infoWindowHtml != "undefined"){
			var info;
			google.maps.event.addListener(marker, "click", function()
			{	
					self.closeInfoWindow();
					google.maps.event.trigger(marker,"mouseout");
					info = new ELabelEx(map, point, place.infoWindowHtml);
					info.pixelOffset=new google.maps.Size(place.infoWindowPixlOffset_x,place.infoWindowPixlOffset_y);
					info.setMap(map);
					place.infoWindow="on";
					self.infoWindow=info;
			});	
		}
		if (typeof place.mouseOverLabelHtml != "undefined") {
			var markerLabel;
			google.maps.event.addListener(marker, "mouseover", function(){
				if (typeof place.infoWindow == "undefined" || place.infoWindow == "off") {
					markerLabel = new ELabel(map, point, place.mouseOverLabelHtml);
					markerLabel.pixelOffset = new google.maps.Size(14, -35);
					markerLabel.setMap(map);
					marker.setIcon(place.hoverImage); // change graphic
				}
			});
			google.maps.event.addListener(marker, "mouseout", function(){
				markerLabel.hide();
				markerLabel.setMap(null);
				marker.setIcon(place.markerImage); // change graphic
			});
		} else if (typeof place.hoverImage != "undefined"){
			google.maps.event.addListener(marker, "mouseover", function(){
					marker.setIcon(place.hoverImage); // change graphic
			});
			google.maps.event.addListener(marker, "mouseout", function(){
				marker.setIcon(place.markerImage); // change graphic
			});
			if (typeof place.name != "undefined")
				marker.setTitle(place.name);
		}
		self.gmarkers.push(marker);
		self.markerBounds.extend(marker.getPosition());
		return marker;
	},
	removeMarker:function(marker,markerArray){
		var self=this,removedMarker;
		markerArray=(markerArray!=null)?markerArray:self.gmarkers;
		marker.setMap(null);
		for (var i=0;i<markerArray.length;i++){
			if (KSR.MapUtil.MarkersEqual(marker,markerArray[i])){
				removedMarker=markerArray.splice(i,1);
				break;
			}
		}
		return removedMarker;
	},
	resetViewport:function(map,bounds){
		var self=this;
		map=(map!=null)?map:self.mapInstance;
		bounds=(bounds!=null)?bounds:self.markerBounds;	
		map.fitBounds(self.markerBounds);
//		console.log("from resetViewport")
//		self.zoomLevelLimited=true;
	},
	closeInfoWindow:function(elabelObj){
		var self=this;
		elabelObj=(elabelObj!=null)?elabelObj:self.infoWindow;
		if (elabelObj!=null){
			elabelObj.setMap(null);
			elabel=null;	
		}
	},
	cleanUpDirections:function(displayOverlay,text_direction_id){
		if (displayOverlay!=null)
			displayOverlay.setMap(null);
	  	$("#"+text_direction_id).html("");
	},
	getDrivingDirections:function(map,text_direction_id,start_address,end_address,callback_func){
		var directionsDisplay = new google.maps.DirectionsRenderer();
		var directionsService = new google.maps.DirectionsService();
		map=(map!=null)?map:self.mapInstance;
		directionsDisplay.setMap(map);
		directionsDisplay.setPanel(document.getElementById(text_direction_id));
		var start;
		var end;
	
	    var request = {
	        origin:start_address, 
	        destination:end_address,
	        travelMode: google.maps.DirectionsTravelMode.DRIVING
	    };
		var s;
	    directionsService.route(request, function(response, status) {
	      if (status == google.maps.DirectionsStatus.OK) {
	        directionsDisplay.setDirections(response);
	      } 
		  callback_func(directionsDisplay,status);
	    });
	},
	getNumberMarkerImage:function(num){
		return new google.maps.MarkerImage(this.settings.markerImageBaseUrl+num+"|"+this.settings.pinColor);
	},
	getNumberMarkerHoverImage:function(num){
		return new google.maps.MarkerImage(this.settings.markerHoverImageBaseUrl+num+"|"+this.settings.pinHoverColor);
	},
	drawPolygon:function(name,coordinates,type,clickCallbackFunc){
		var polygonCoords = [];
		var self = this;
		var bounds = new google.maps.LatLngBounds();
		if (type === "target"){
			var color = "#ff0000";
		} else {
			var color = "#777";
		}
		for ( var i = 0; i < coordinates.length; i++) {
			polygonCoords[i] = [];
			for ( var j = 0; j < coordinates[i].length; j++) {
				polygonCoords[i][j] = new google.maps.LatLng(coordinates[i][j].y,coordinates[i][j].x);
				bounds.extend(polygonCoords[i][j]);
				if (!self.markerBounds.contains(polygonCoords[i][j]))
					self.markerBounds.extend(polygonCoords[i][j]);
			}
		}
		var polygon = new google.maps.Polygon({
		    paths: polygonCoords,
		    strokeColor: color,
		    strokeOpacity: 0.8,
		    strokeWeight: 2,
		    fillColor: color,
		    fillOpacity: 0.2,
		    map:self.mapInstance
		  });
		var infoLabel ;
		var mouseover = google.maps.event.addListener(polygon,'mouseover',function(){
			polygon.setOptions({
			    strokeColor: '#0000ff',
			    fillColor: '#0000ff'
			});
			infoLabel = new ELabel(self.mapInstance,bounds.getCenter(),"<div class='info-label'><strong>"+name+"</strong></div>");
//			infoLabel = new ELabelEx(self.mapInstance,bounds.getCenter(),"<div class='info-label'><strong>"+name+"</strong></div>");
//			infoLabel.pixelOffset = new google.maps.Size(-15,0);
			infoLabel.setMap(self.mapInstance);
		});
		var mouseout=google.maps.event.addListener(polygon,'mouseout',function(){
			polygon.setOptions({
			    strokeColor: color,
			    fillColor: color
			})	
			infoLabel.setMap(null);
			infoLabel=null;
		});
		if (typeof clickCallbackFunc === 'function'){
			var mouseout=google.maps.event.addListener(polygon,'click',function(){
				clickCallbackFunc(name);
			});
		}
		return polygon;
	},
	drawCircle:function(center){
		var self = this;
		var circleOptions = {
			      strokeColor: '#FF0000',
			      strokeOpacity: 0.5,
			      strokeWeight: 1,
			      map:self.mapInstance,
			      fillColor: '#FF0000',
			      fillOpacity: 0.1,
			      center: new google.maps.LatLng(center.lat,center.lng),
			      radius: center.searchRadius
			    };
		return new google.maps.Circle(circleOptions);
	}
	
}
